package db

import (
	"time"
	"encoding/json"
	"github.com/globalsign/mgo/bson"
	"adai.design/homeserver/log"
)

// 配件注册信息
type Register struct {
	// 设备ID与登入密钥
	Id 					string		`json:"id" bson:"id"`
	PrivateKey 			string		`json:"private_key" bson:"private_key"`

	// 设备信息(名称-制造商-型号-序列号-固件版本)
	Name 				string		`json:"name,omitempty" bson:"name,omitempty"`
	Manufacturer		string		`json:"manufacturer,omitempty" bson:"manufacturer,omitempty"`
	Model 				string		`json:"model,omitempty" bson:"model,omitempty"`
	SerialNumber 		string		`json:"serial_number,omitempty" bson:"serial_number,omitempty"`
	FirmwareRevision 	string		`json:"firmware,omitempty" bson:"firmware,omitempty"`

	// 家庭信息与时间
	HomeId  	string			`json:"home_id,omitempty" bson:"home_id,omitempty"`
	Time 		time.Time		`json:"-" bson:"time"`		// 注册时间
	Date 		string			`json:"date" bson:"-"`
}

func GetRegisterById(id string) (*Register, error) {
	session, err := getSession()
	if err != nil {
		return nil, err
	}
	defer session.Close()

	// 查找插入的设备
	collection := session.DB(dbName).C(collectionAccessory)
	var register *Register
	err = collection.Find(bson.M{"id": id}).One(&register)
	if err != nil {
		return nil, err
	}
	return register, nil
}

func (r *Register) String() string {
	r.Date = r.Time.In(time.Local).Format("2006-01-02 15:04:05")
	buf, _ := json.Marshal(r)
	return string(buf)
}

func (r *Register) Online() {
	session, err := getSession()
	if err != nil {
		return
	}
	defer session.Close()

	status := AccessoryStatus{
		Id: r.Id,
		State: AccessoryStateOnline,
		Time: time.Now(),
	}

	collection := session.DB(dbName).C(collectionAccessoryLog)
	err = collection.Insert(status)
	if err != nil {
		log.Error("err: %s", err)
	}
}

func (r *Register) Offline() {
	session, err := getSession()
	if err != nil {
		return
	}
	defer session.Close()
	status := AccessoryStatus{
		Id: r.Id,
		State: AccessoryStateOffline,
		Time: time.Now(),
	}

	collection := session.DB(dbName).C(collectionAccessoryLog)
	err = collection.Insert(status)
	if err != nil {
		log.Error("err: %s", err)
	}
}

// 设备在线信息
const (
	AccessoryStateOnline = "online"
	AccessoryStateOffline = "offline"
)

type AccessoryStatus struct {
	Id 			string		`json:"id" bson:"id"`
	State 		string		`json:"state" bson:"state"`
	Time 		time.Time	`json:"-" bson:"time"`
	Date 		string		`json:"date" bson:"-"`
}

func (a *AccessoryStatus) String() string {
	a.Date = a.Time.In(time.Local).Format("2006-01-02 15:04:05")
	buf, _ := json.Marshal(a)
	return string(buf)
}
















